<template>
  <view class="w-full max-w-[750rpx] mx-auto min-h-screen bg-[#f6f8fa] p-[32rpx] box-border">
    <backView />
    <text class="block text-[48rpx] font-extrabold mb-[40rpx] text-center text-blue-600 drop-shadow">新增{{PageItem.title}}</text>
    <FormView :fieldConfig="fieldConfig" :form="form" :showButtons="true" @submit="submitForm" />
  </view>
</template>

<script setup lang="ts">
import { reactive, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import { assessSpecialFields as fieldConfig } from './fields'
import FormView from '@/components/FormView.vue'
import { request } from '@/service/request'
import { PageItem } from './fields'
import { localStg } from '@/utils'
import backView from '@/components/backView.vue'

onMounted(async () => {
  console.log('新增页面加载')
  const obj = localStg.get("demographicInfo");
  if(obj){
    form.name = obj.name;
    form.idNumber = obj.idNumber;
    form.assessid = obj.recordid;
  }
})

const form = reactive<any>({})

async function submitForm(form: any, fieldConfig: any) {
  try {
    // 表单验证
    // if (!form.name) {
    //   Taro.showToast({ title: '请输入姓名', icon: 'error' })
    //   return
    // }
    // if (!form.sex) {
    //   Taro.showToast({ title: '请选择性别', icon: 'error' })
    //   return
    // }

    // 提交数据
    const params = {
      ...form,
      age: form.age ? parseInt(form.age) : null
    }
    
    const result = await request.post<any>(PageItem.commUrl + `/add`, params, {
      useErrMsg: true
    })
    if(result?.error?.message){
      Taro.showToast({ title: result.error.message, icon: 'error' })
      return
    }
    console.log("result", result)
    if (result) {
      Taro.showToast({ title: '添加成功', icon: 'success' })
      // 返回上一页
      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    }
  } catch (error) {
    console.error('保存失败:', error)
    Taro.showToast({ title: '保存失败', icon: 'error' })
  }
}
</script>
